#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "servicedao.h"
#include "servicedao_file_impl.h"
#include "department.h"

using namespace MH;

//从文件读入
void ServiceDaoFileImpl::load(vector<Department>& vecDepts)
{
	int fd = open("services.dat",O_RDONLY,0644);
	if(0 > fd)
	{
		perror("open");
		exit(-1);
	}
	
	while(1)
	{
		int sub_id = 0;
		int len_name = 0;
		int count = 0;

		int rd = read(fd,&sub_id,sizeof(int));
		if(rd <= 0 || 0 == sub_id)
		{
			break;
		}

		rd = read(fd,&len_name,sizeof(int));
		char *sub_name = new char[len_name];
		sub_name[len_name] = '\0';
		rd = read(fd,sub_name,len_name);
	
		read(fd,&count,sizeof(int));
		

		Department dep(sub_id,sub_name);

		
		for(int i = 0;i < count;i++)
		{
			int e_id = 0;
			read(fd,&e_id,sizeof(int));

			int len_e_name = 0;
			read(fd,&len_e_name,sizeof(int));
			char *e_name = new char[len_e_name];
			e_name[len_e_name] = '\0';
			read(fd,e_name,len_e_name);


			bool e_gender = true;
			read(fd,&e_gender,sizeof(bool));


			int e_age = 0;
			rd = read(fd,&e_age,sizeof(int));

			Employee emp(e_id,e_name,e_gender,e_age);
			dep.m_vecEmps.push_back(emp);
		}
		vecDepts.push_back(dep);
		if(0 >= rd)
		{
			break;
		}
	}

	close(fd);
}

void ServiceDaoFileImpl::save(vector<Department>& vecDepts)
{
	int fd = open("services.dat",O_WRONLY | O_TRUNC,0644);
	if(0 >= fd)
	{
		perror("open");
		exit(-1);
	}
	
	for(unsigned int i = 0;i < vecDepts.size();i++)
	{
		Department tmp = vecDepts[i];

		int sub_id = tmp.m_nid;
		write(fd,&sub_id,sizeof(int));

		char *sub_name = const_cast<char *>(tmp.m_strName.c_str());
		int len_name = tmp.m_strName.size();
		unsigned int num_emp  = tmp.m_vecEmps.size();

		write(fd,&len_name,sizeof(int));
		write(fd,sub_name,len_name);

		write(fd,&num_emp,sizeof(unsigned int));

		vector<Employee> emp = tmp.m_vecEmps;
		for(unsigned int j = 0;j < num_emp;j++)
		{
			sub_id = emp[j].m_nid;

			sub_name = const_cast<char *>(emp[j].m_strName.c_str());
			len_name = emp[j].m_strName.size();

			bool sub_gender = emp[j].m_bGender;
			int  sub_age = emp[j].m_nAge;

			write(fd,&sub_id,sizeof(int));
			
			write(fd,&len_name,sizeof(int));
			write(fd,sub_name,len_name);

			write(fd,&sub_gender,sizeof(bool));
			write(fd,&sub_age,sizeof(int));

		}

	}
	close(fd);

}

